#define _POSIX_SOURCE
#define _BSD_SOURCE

#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include "rngs.h"

#ifndef MAX_PLAYER
#define MAX_PLAYER 4
#endif

#ifndef MAX_SUPP
#define MAX_SUPP 13
#endif

#ifndef SKEW_CHANCE
#define SKEW_CHANCE 4
#endif

int checkIsGameOver(int expected, struct gameState *post)
{
	int result;

	result = isGameOver(post);
	assert(result == expected);

	return 0;
}

void sigabrt_catch(int sig)
{
	printf("SIGABRT has been caught\n");
	exit(0);
}

int main(int argc, char **argv)
{
	int i, n, expected, supp_at_0 = 0;

	struct gameState G;

	signal(SIGABRT, sigabrt_catch);

	printf("Testing isGameOver.\n");

	printf("RANDOM TESTS.\n");

	/* Set Random Number Generator */
	SelectStream(2);
	PutSeed(3);

	for (n = 1; n <= 20000; n++) {
		supp_at_0 = 0;

		for (i = 0; i < sizeof(struct gameState); i++) {
			((char *) &G)[i] = floor(Random() * 256);
		}
		

		/* Randomly Set Game Numbers */ 
		for (i = 0; i < (treasure_map + 1); i++) {
			G.supplyCount[i] = floor(Random() * MAX_SUPP);
			if (G.supplyCount[i] == 0) {
				supp_at_0++;
			}
		}

		if (argc > 1 && strcmp(argv[1], "-v") == 0) {
			printf("Test #%5d: province = %2d supply@0 = %2d\n", n, G.supplyCount[province], supp_at_0);
		}
		
		if ((G.supplyCount[province] == 0) || (supp_at_0 >= 3)) {
			expected = 1;
		} else {
			expected = 0;
		}

		checkIsGameOver(expected, &G);
	}

	printf ("ALL TESTS OK\n");

	return 0;
}
